# 交通安全综合服务平台

import sys
import time

from urllib.request import urlopen

import cv2
import os

import random
import numpy as np

from selenium import webdriver
from selenium.webdriver import ActionChains

from selenium.webdriver.common.by import By

wait_time_short = 1
wait_time1_long = 2


class jtaq(object):

    def __init__(self, user_name, password):

        # 当前py路径同一层级 下加pic文件
        self.save_dir = sys.path[0] + "/pic/"

        self.tryNum = 1
        self.user_name = user_name
        self.password = password
        # 设置驱动路径
        executable_path = r"/python/python/python_ty/gtly/chromedriver"
        # 设置options参数
        option = webdriver.ChromeOptions()
        # 浏览器不提供可视化界面
        option.add_argument('--headless')
        # 隐藏正受到自动测试软件的控制
        option.add_experimental_option("excludeSwitches", ["enable-automation"])
        # 指定浏览器分辨率
        #option.add_argument('window-size=1920x1080')
        # 最大化运行/全屏窗口
        # option.add_argument('--start-maximized')
        #cls.driver = webdriver.Chrome(executable_path=executable_path, options=option)

        option.add_argument("--disable-gpu")
        option.add_argument('--no-sandbox')
        option.add_argument('--remote-debugging-port=9222')
        option.add_argument('--disable-dev-shm-usage')


        self.driver = webdriver.Chrome(executable_path=executable_path,options=option)



    def getLogin(self):
        login_url = "https://yn.122.gov.cn"
        self.driver.get(login_url)
        time.sleep(wait_time1_long)
        # 点击企业登录
        self.driver.find_element(By.XPATH, '//*[@id="loginDiv"]/div[2]/button').click()
        time.sleep(wait_time1_long)

        # 过登录验证
        self.verification_code(0)

        # 输入用户名
        self.driver.find_element(By.XPATH, '/html/body/div[3]/div/div[1]/div/div[2]/form[1]/div[1]/div/input').clear()
        self.driver.find_element(By.XPATH,
                                 '/html/body/div[3]/div/div[1]/div/div[2]/form[1]/div[1]/div/input').send_keys(self.user_name)

        # 输入密码
        self.driver.find_element(By.XPATH, '/html/body/div[3]/div/div[1]/div/div[2]/form[1]/div[2]/div/input').clear()
        self.driver.find_element(By.XPATH,
                                 '/html/body/div[3]/div/div[1]/div/div[2]/form[1]/div[2]/div/input').send_keys(self.password)

        # 勾选同意证书
        self.driver.find_element(By.XPATH, '//*[@id="login2"]/div[4]/div/label/input').click()

        # 点击登录
        self.driver.find_element(By.ID, 'btnQyyhdl').click()

        # cookies = "JSESSIONID-L=" + self.driver.get_cookie("JSESSIONID-L")['value'] + "; " + "_uab_collina=" + \
        #           self.driver.get_cookie("_uab_collina=")['value'] + "; " + "accessToken=" + \
        #           self.driver.get_cookie("accessToken")['value'] + "; " + "JSESSIONID=" + \
        #           self.driver.get_cookie("JSESSIONID")['value'] + "; " + "c_yhlx_=" + \
        #           self.driver.get_cookie("c_yhlx_")['value'] + "; " + "tmri_csfr_token=" + \
        #           self.driver.get_cookie("tmri_csfr_token")['value']


        cookies = f"JSESSIONID-L={self.driver.get_cookie('JSESSIONID-L')['value']}; " \
                  f"_uab_collina={self.driver.get_cookie('_uab_collina')['value']}; " \
                  f"accessToken={self.driver.get_cookie('accessToken')['value']}; " \
                  f"JSESSIONID={self.driver.get_cookie('JSESSIONID')['value']}; " \
                  f"c_yhlx_={self.driver.get_cookie('c_yhlx_')['value']}; " \
                  f"tmri_csfr_token={self.driver.get_cookie('tmri_csfr_token')['value']}"

        # cookies = self.driver.get_cookie("_uab_collina")
        return cookies

    def verification_code(self, offset):
        # 小的哪个缺口图片
        small_pic_pattern = '//*[@id="slide2"]/div/div[1]/img[2]'
        small_url = self.driver.find_element(By.XPATH, small_pic_pattern).get_attribute('src')

        # print(small_url)
        # url("https://t.captcha.qq.com/cap_union_new_getcapbysig?img_index=0&image=02442700005fef3e0000000bb5d7a99e3988&sess=s0MyZoNAtLY2oBqoP886sYZ9lJ6f4Fk5S3pmzTgw7Dkgbo9-8T8c9Fe2TWyIKxzF8He5sAgef9oljHR3nGJRXUoxxR0lXE2rAAZ5vGqIu9-CUjqCiupd29e2emUR9mkm1ff-p2qeG66q4a5LUL8ZEBJBJHG-CfMRNFRMT71oveCCiz46Y7sIXQVSQCj3ZzalXFhLx7YebZurGoFqCl1_toIMw-bE8bNijkbQORIzEVmuIsoyTCmTaWSoL-c4nqDq_iAohOMa4CtY76HOuZ3QPcPMC_uxu3UfKZyA5DC9mV3AGFDYaRAOjU_2rvFhMRG2lJsCM1h6FgxXMYrCZ96SPmX_56VweA_0CfBaMtmUigZ3V2ReYgYjUPew**")
        # print("small_url:", small_url)

        # 大的背景图片
        big_pic_pattern = '//*[@id="slide2"]/div/div[1]/img[1]'
        big_url = self.driver.find_element(By.XPATH, big_pic_pattern).get_attribute('src')
        # print("big_url:", big_url)

        distance = self.get_distance(small_url, big_url)
        distance = (distance - offset)
        # print("distance:", distance)
        # 下面的滑块非图片缺口
        element = self.driver.find_element(By.CLASS_NAME, 'scroll_Thumb')
        ActionChains(self.driver).click_and_hold(element).perform()
        time.sleep(0.5)
        # steps = self.get_steps(distance)
        steps = []
        steps.append(distance)

        # print("steps:", steps)
        for step in steps:
            ActionChains(self.driver).move_by_offset(step, random.randint(-1, 1)).perform()
            time.sleep((random.randint(5, 15) / 1000))

        ActionChains(self.driver).release(on_element=element).perform()
        time.sleep(1)
        try:
            self.driver.find_element(By.CLASS_NAME, 'icon-ok')
            print("验证成功")
        except:
            print(f"第{self.tryNum}次验证失败")
            self.tryNum = self.tryNum + 1
            if self.tryNum <= 10:
                self.verification_code(0)
            else:
                return print("滑块验证过程验证失败超过10次，自动结束")

    def get_steps(self, dis):
        # 计算公式：v=v0+at, s=v0t+½at², v²-v0²=2as
        v = 0
        t = 0.3
        steps = []
        current = 0
        mid = dis / 2
        while current < dis:
            if current < mid:
                a = 2
            else:
                a = -2
            v0 = v
            s = v0 * t + 0.5 * a * (t ** 2)
            current += s
            steps.append(round(s))
            v = v0 + a * t
        return steps

    def get_distance(self, small_url, big_url):
        s_img = self.download_img(small_url, 'small')
        time.sleep(2)
        b_img = self.download_img(big_url, 'big')
        # print("s_img:", s_img)
        # print("b_img:", b_img)
        small_pic = cv2.Canny(cv2.GaussianBlur(cv2.imread('pic/small.png'), (5, 5), 0), 100, 300)

        big_pic = cv2.Canny(cv2.GaussianBlur(cv2.imread('pic/big.png'), (5, 5), 0), 100, 300)

        res = cv2.matchTemplate(big_pic, small_pic, cv2.TM_CCOEFF_NORMED)
        x, y = np.unravel_index(res.argmax(), res.shape)
        # min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        # print('max_loc[0]:', max_loc[0])
        # print(x)
        # print(y)
        return y

    # 下载图片,url是图片地址，size_type是想要保存的图片名字
    def download_img(self, url, size_type):

        # 设置我要保存的图片的路径
        path = self.save_dir + size_type + '.png'

        if not os.path.exists(self.save_dir):
            os.makedirs(self.save_dir)

        with urlopen(url) as response, open(path, 'wb') as f:
            f.write(response.read())

        return f.name


# if __name__ == '__main__':
#     #driver_path = r"D:\tools\pythonItem\python\python_ty\chromedriver.exe"
#     user_name = '53042009017209'
#     password = 'yd123456'
#     jtaq = jtaq(user_name, password)
#     print(jtaq.getLogin())
